package Send2ME::Magic::Magic;

use Exporter 'import';

@EXPORT = qw(variables isAcceptable isPerlScriptAcceptable isPerlVariableAcceptable locale);

sub isAcceptable {
	my $recipient = shift;
	return $recipient =~ m/^[a-zA-Z\d]+$/;
}

sub variables_rec {
	my $in = shift;
	$in =~ s/^\s+|\s+$//g;
	
	if ($in =~ /^\((.*)\)$/) { 
		# ( $1 )
		return variables_rec($1);
	}
	
	if ($in =~ /^(.*?),(.*)$/) {
		return (variables_rec($1), variables_rec($2));
	}

	return ($in);
}

sub variables {
	my $in = shift;
	
	$in =~ s/split|join//g;
	$in =~ s/','|","//g;
	
	return variables_rec($in);
}

sub isPerlVariableAcceptable {
	my $variable = shift;
	
	return 0 unless ($variable);
	
	return $variable eq '$from' ||
			$variable eq '$subject' ||
			$variable eq '$body' ||
			$variable eq '$1' ||
			$variable eq '$2' ||
			$variable eq '$3' ||
			$variable eq '$4' ||
			$variable eq '$5' ||
			$variable eq '$6' ||
			$variable eq '$7' ||
			$variable eq '$8' ||
			$variable eq '$9' ||
			$variable =~ /^\$header\{'[^']*'\}$/ ||
			$variable =~ /^'([^'])'$/ ||
			$variable =~ /^"([^"])"$/;
}

sub isPerlScriptAcceptable {
	my $script = shift;

	unless ($script) {
		$_ = 'Empty script is not allowed';
		return 0;
	}

	if ( $script =~ m|^\s*(\$[^;,=\s]+)\s*=~\s*/(.+)/[^;,]*;*\s*$| ) {
		my $variable = $1;
		
		unless (isPerlVariableAcceptable($variable)) {
			$_ = 'You can use only $from, $subject, $body, $header{\'name\'}, $1-$9 variables, not ' . $variable;		
			return 0;
		}
		
		my $pattern = $2;
		eval { qr/$pattern/ };
		
		if ($@) {
			$_ = $@;
			return 0;
		}

		return 1;
	}

	$_ = 'Only "$var =~ /regex/" is acceptable';
	return 0;
}

sub locale {
	my ($accepts, @locales) = @_;
	
	if ($accepts) {
		my @accepts = split(';', $accepts);
		
		foreach (@accepts) {
			my $a = $_;
			foreach (@locales) {
				my $l = $_;
				
				if ($a =~ m/$l/i) {
					return $l;
				}
			}
		}
	}
	
	return $locales[0];
}

1;
